<script setup lang="ts">
import { ref, watch, onMounted } from "vue";
import { message } from "@/utils/message";
import { FormInstance } from "element-plus";
import { useCallAPI } from "../utils/hook";
import { getAccount } from "@/utils/auth";
import { appType } from "@/store/types";
import { pubApiEventEmitter } from "@/utils/eventBus";
import { serviceType } from "@/utils/commonType";

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  data: {
    type: Object as PropType<serviceType>,
    default: () => {
      return {
      };
    }
  },
  appList: {
    type: Object as PropType<appType>,
    default: () => {
      return {
      };
    }
  },
  curAppId: {
    type: String,
    default: () => {
      return "";
    }
  }
});
const {
  onAddServiceInfo
} = useCallAPI();

const ruleFormRef = ref<FormInstance>();

const formVisible = ref(false);
const formData = ref({ ...props.data });
const emit = defineEmits(["update:visible"]);
const submitForm = (formEl: FormInstance | undefined) => {

  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      let serviceName = formData.value.serviceName;
      formData.value.tenantId = getAccount().tenantId;
      onAddServiceInfo(formData.value).then(function (data) {
        resetForm(formEl);
        message(`保存服务【${serviceName}】成功`, {
          type: "success"
        });
        formVisible.value = false;
        try {
          pubApiEventEmitter.emit("clickAppTreeNode", { pid: 'root' });
        } catch (err) {
          message(`刷新信息异常：${err.message}`, {
            type: "error"
          });
        }

      }).catch(function (err) {
        message(`保存服务【${serviceName}】异常：${err.message}`, {
          type: "error"
        });
      });
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {

  if (!formEl) return;
  formEl.resetFields();
};

const closeDialog = () => {
  formVisible.value = false;
  resetForm(ruleFormRef.value);
};


watch(
  () => formVisible.value,
  val => {
    emit("update:visible", val);
  }
);

watch(
  () => props.visible,
  val => {
    formVisible.value = val;
  }
);

watch(
  () => props.data,
  val => {
    formData.value = val;
  }
);
watch(() => props.curAppId,
  val => {
    formData.value = {
      ...formData.value,
      appId: val === "root" ? "" : val
    };
  });
const REGEXP_URL = /\/[^\s/$.?#].[^\s]*$/
const rules = {
  serviceName: [{ required: true, message: "服务名称不能为空", trigger: "blur" }],
  appId: [{ required: true, message: "服务所属应用必选", trigger: "blur" }],
  serviceUri: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (value === "") {
          callback(new Error("服务URI不能为空"));
        } else if (!REGEXP_URL.test(value)) {
          callback(new Error("URI地址格式错误"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ],
};


</script>

<template>
  <el-dialog v-model="formVisible" title="新建API服务" :width="680" draggable :before-close="closeDialog">
    <!-- 表单内容 -->
    <el-form ref="ruleFormRef" :model="formData" :rules="rules" label-width="120px">
      <el-form-item label="服务名称" prop="serviceName">
        <el-input v-model="formData.serviceName" :style="{ width: '480px' }" placeholder="请输入API服务名称" />
      </el-form-item>

      <el-form-item label="服务发布URI" prop="serviceUri">
        <el-input v-model="formData.serviceUri" :style="{ width: '480px' }" placeholder="请输入服务发布URI" />
      </el-form-item>
      <el-form-item label="服务所属应用" prop="appId">
        <el-select v-model="formData.appId" clearable :style="{ width: '480px' }">
          <el-option v-for="item in props.appList " :key="item.pid" :value="item.pid" :label="item.appName">
            {{ item.appName }}
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="服务说明" prop="serviceDesc">
        <el-input v-model="formData.serviceDesc" type="textarea" :style="{ width: '480px' }" placeholder="请输入服务说明" />
      </el-form-item>

    </el-form>
    <template #footer>
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>
